package com.rightsidetech.http.controller.storeApp.activity;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.activity.dto.request.store.MtUploadPicReq;
import com.rightsidetech.activity.dto.response.store.app.CompareActResp;
import com.rightsidetech.activity.dto.response.store.app.MtActivityRecordDetailResp;
import com.rightsidetech.activity.dto.response.store.app.MtAppDetailResp;
import com.rightsidetech.activity.dto.response.store.app.MtAppHomeResp;
import com.rightsidetech.activity.entity.*;
import com.rightsidetech.activity.service.MtActivityAppService;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.StoreActivityEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.DateUtil;
import com.rightsidetech.commom.utils.IKExpressionUtil;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.dtos.request.IdReq;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.service.SysStoreInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.util.*;

@Api(tags = "门店活动相关")
@RestController
@RequestMapping("/storeApp/activity")
@ShenyuSpringMvcClient(path = "/storeApp/activity/**")
public class MtActivityAppController extends BaseController {

    @Resource
    private MtActivityAppService mtActivityAppService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;

    @Log
    @Token
    @GetMapping("/list")
    @ApiOperation("活动列表")
    public ResponseData<List<MtAppHomeResp>> homePage() {
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        ResponseData<List<MtAppHomeResp>> data = mtActivityAppService.list(StoreActivityEnum.BM001.getDicCode());
        List<MtAppHomeResp> list = data.getResData();
        Iterator<MtAppHomeResp> iter = list.iterator();
        while (iter.hasNext()) {
            MtAppHomeResp resp = iter.next();
            MtActivityRule activityRule = mtActivityAppService.selectRuleByMoldAndActId(resp.getId(), StoreActivityEnum.CY000.getDicType());
            if (ObjectUtil.isEmpty(activityRule)) {
                continue;
            }
            if (!cyRule(activityRule, storeInfo.getSysAgentInfoId(), storeInfo.getGrade())) {
                iter.remove();
            }
        }
        for (MtAppHomeResp homeResp : list) {
            MtUserJoinActivityApply apply = mtActivityAppService.selectUserJoinByIdAndUId(homeResp.getId(), storeInfo.getId());
            homeResp.setApplyStatus(ObjectUtil.isEmpty(apply) ? null : apply.getStatus());
            List<MtActivityRule> sbRule = mtActivityAppService.selectRuleList(homeResp.getId(), StoreActivityEnum.SB001.getDicType());
            //报名状态 0报名未开始 1报名进行中 2报名已结束
            byte enrollStatus = 1;
            for (MtActivityRule rule : sbRule) {
                if (rule.getExpressionField().equals(StoreActivityEnum.SB001.getDicCode())) {
                    homeResp.setEnrollStartTime(rule.getConditionValue());
                    Date enrollStartTime = DateUtil.parseDateStr(rule.getConditionValue());
                    if (!StringUtils.isEmpty(enrollStartTime)){
                        if (enrollStartTime.after(new Date())){
                            enrollStatus = 0;
                        }
                    }
                } else {
                    homeResp.setEnrollEndTime(rule.getConditionValue());
                    Date enrollEndTime = DateUtil.parseDateStr(rule.getConditionValue());
                    if (!StringUtils.isEmpty(enrollEndTime)){
                        if (enrollEndTime.before(new Date())){
                            enrollStatus = 2;
                        }
                    }
                }
            }
            homeResp.setEnrollStatus(enrollStatus);
            //活动状态 0未开始 1进行中 2已结束
            byte activityStatus = 1;
            Date startTime = homeResp.getStartTime();
            if (!StringUtils.isEmpty(startTime)){
                if (startTime.after(new Date())){
                    activityStatus = 0;
                }
            }
            Date endTime = homeResp.getEndTime();
            if (!StringUtils.isEmpty(endTime)){
                if (endTime.before(new Date())){
                    activityStatus = 2;
                }
            }
            homeResp.setActivityStatus(activityStatus);
        }
        return data;
    }


    @Log
    @Token
    @PostMapping("/join")
    @ApiOperation("参加活动")
    public ResponseData joinAct(@RequestBody IdReq req) {
        MtActivity activity = mtActivityAppService.selectMtActivity(req.getId());
        if (ObjectUtil.isEmpty(activity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找要参加的活动");
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        if (activity.getStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "活动状态不正确");
        }
        MtUserJoinActivityApply apply = mtActivityAppService.selectUserJoinByIdAndUId(req.getId(), storeInfo.getId());
        if(ObjectUtil.isNotEmpty(apply)){
            return ResponseData.fail("你已经参加了此活动");
        }
        if (!isEnrollTime(activity.getId())) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未在报名时间内");
        }
        if (activity.getStatus() != 1) {
            return ResponseData.fail("活动状态不正确");
        }
        MtActivityRule bmRule = mtActivityAppService.selectRuleByFieldAndActId(activity.getId(), StoreActivityEnum.BM001.getDicCode());
        if (ObjectUtil.isEmpty(bmRule)) {
            return ResponseData.fail("此活动非手动参加的活动");
        }
        MtActivityRule rule = mtActivityAppService.selectRuleByMoldAndActId(req.getId(), StoreActivityEnum.CY000.getDicType());
        if (!cyRule(rule, storeInfo.getSysAgentInfoId(), storeInfo.getGrade())) {
            return ResponseData.fail("不满足该活动的需求");
        }
        MtUserJoinActivityApply record = new MtUserJoinActivityApply();
        record.setActId(req.getId());
        record.setActName(activity.getName());
        record.setActStart(activity.getStartTime());
        record.setActEnd(activity.getEndTime());
        record.setUserAccountId(storeInfo.getId());
        record.setUserLoginName(storeInfo.getStoreName());
        record.setUserPhone(storeInfo.getConnectWay());
        record.setJoinTime(new Date());
        if (mtActivityAppService.insertUserJoin(record) <= 0) {
            return ResponseData.fail("参加活动失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    /**
     * @return true可以参加活动
     */
    private boolean cyRule(MtActivityRule rule, Long agentId, Long grade) {
        if (rule.getExpressionField().equals(StoreActivityEnum.CY001.getDicCode())) {
            List<Long> ids = JSONUtil.toList(rule.getExpression(), Long.class);
            return ArrayUtils.contains(ids.toArray(), agentId);
        } else if (rule.getExpressionField().equals(StoreActivityEnum.CY002.getDicCode())) {
            if (ObjectUtil.isEmpty(grade)) {
                return false;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("grade", grade);
            return IKExpressionUtil.executeIs("grade" + rule.getExpression(), map);
        }
        return false;
    }

    @Log
    @Token
    @GetMapping("/detail")
    @ApiOperation("活动详情页")
    public ResponseData<MtAppDetailResp> detail(@RequestParam(value = "id", required = true) Long id) {
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        MtUserJoinActivityApply userJoin = mtActivityAppService.selectUserJoinByIdAndUId(id, storeInfo.getId());
        if (ObjectUtil.isEmpty(userJoin)) {
            return ResponseData.fail("还没参加此活动");
        }
        MtActivity activity = mtActivityAppService.selectBaseById(id);
        if (ObjectUtil.isEmpty(activity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到该活动");
        }
        MtActivityRule hjRule = mtActivityAppService.selectRuleByMoldAndActId(activity.getId(), StoreActivityEnum.HJ000.getDicType());
        if (ObjectUtil.isEmpty(hjRule)) {
            return ResponseData.fail("未找到活动规则");
        }
        MtAppDetailResp result = new MtAppDetailResp();
        result.setApplyStatus(userJoin.getStatus());
        result.setId(activity.getId());
        result.setPicture(activity.getPosterPic());
        result.setRuleDetail(mtActivityAppService.selectRuleDetail(activity.getId()));
        result.setField(hjRule.getExpressionField());
        result.setStartTime(cn.hutool.core.date.DateUtil.format(activity.getStartTime(), "yyyy-MM-dd"));
        result.setEndTime(cn.hutool.core.date.DateUtil.format(activity.getEndTime(), "yyyy-MM-dd"));
        result.setActStatus(activity.getStatus());
        result.setBackgroundPic(activity.getBackgroundPic());
        result.setConditionValue(hjRule.getConditionValue());
        result.setAwardStandard(hjRule.getExpressionField());
        MtActivityRule pbRule = mtActivityAppService.selectRuleByMoldAndActId(id, StoreActivityEnum.PB000.getDicType());
        boolean isCompare = ObjectUtil.isNotEmpty(pbRule);
        if(isCompare){
            result.setPbRule(pbRule.getExpressionField());
            result.setRankValue(pbRule.getConditionValue());
        }
        result.setIsCompare(isCompare);
        if (StoreActivityEnum.HJ002.getDicCode().equals(result.getField())) {
            result.setDownPic(mtActivityAppService.selectPicListByActId(activity.getId()));
            //集赞活动返回后台上传的活动图片
            result.setUpPic(mtActivityAppService.selectProcessPic(storeInfo.getId(), id));
            MtUserJoinActivityProcess process = mtActivityAppService.processByActIdAndCode(activity.getId(), null, storeInfo.getId());
            if(ObjectUtil.isNotEmpty(process)){
                result.setGreat(process.getBizValue());
            }
        } else if (StoreActivityEnum.HJ001.getDicCode().equals(result.getField())) {
            //订单活动返回活动卖出的订单数量
            result.setValueCount(mtActivityAppService.processCount(id, storeInfo.getId()));

        } else if (StoreActivityEnum.HJ003.getDicCode().equals(result.getField())) {
            //堆头活动返回已上传的图片
            result.setTodayIsUp(ObjectUtil.isNotEmpty(mtActivityAppService.processByActIdAndCode(activity.getId(), (byte) 1, storeInfo.getId())));
            result.setUpPic(mtActivityAppService.selectProcessPic(storeInfo.getId(), id));
        } else if (StoreActivityEnum.HJ004.getDicCode().equals(result.getField())) {
            //销量活动返回活动内的销量
            result.setValueCount(mtActivityAppService.processCount(id, storeInfo.getId()));
        }
        MtActivityRule rule = mtActivityAppService.selectRuleByMoldAndActId(id, StoreActivityEnum.CJ000.getDicType());
        boolean empty = ObjectUtil.isEmpty(rule);
        result.setDicCode(empty ? null : rule.getExpressionField());
        if (!empty) {
            if (StoreActivityEnum.CJ002.getDicCode().equals(rule.getExpressionField())) {
                //返回剩余抽奖次数
                result.setRemain(getRemain(activity.getId(), storeInfo.getId(), hjRule));
                result.setLottery(mtActivityAppService.selectLotteryResp(activity.getId(), storeInfo.getId()));
            }
        }
        List<CompareActResp> compareList = null;
        if(StoreActivityEnum.HJ002.getDicCode().equals(result.getField()) && isCompare){
            if (StoreActivityEnum.PB001.getDicCode().equals(rule.getExpressionField())) {
                //全部排名
                compareList = mtActivityAppService.selectCompareActJiZan(activity.getId(), null);
            } else if (StoreActivityEnum.PB002.getDicCode().equals(rule.getExpressionField())) {
                //大区排名
                compareList = mtActivityAppService.selectCompareActJiZan(activity.getId(), storeInfo.getAreaId());
            }
        }else {
            if (isCompare) {
                result.setRankValue(pbRule.getConditionValue());
                if (StoreActivityEnum.PB001.getDicCode().equals(pbRule.getExpressionField())) {
                    //全部排名
                    compareList = mtActivityAppService.selectCompareAct(id, null);
                } else if (StoreActivityEnum.PB002.getDicCode().equals(pbRule.getExpressionField())) {
                    //大区排名
                    compareList = mtActivityAppService.selectCompareAct(id, storeInfo.getAreaId());
                }
            }
        }
        result.setRanking(getRanking(compareList,storeInfo.getId()));

        //判断是否在领奖时间内
        List<MtActivityRule> sbRule = mtActivityAppService.selectRuleList(id, StoreActivityEnum.LT000.getDicType());
        //是否在领奖时间内  0领奖前 1领奖中 2领奖结束
        byte rewardStatus = 1;
        if (CollectionUtils.isEmpty(sbRule)){
            for (MtActivityRule rewardRule : sbRule) {
                if (StoreActivityEnum.LT001.getDicCode().equals(rewardRule.getExpressionField())){
                    Map<String, Object> map = new HashMap<>();
                    map.put("date", new Date());
                    if (!IKExpressionUtil.executeIs("date" + rewardRule.getExpression(), map)){
                        rewardStatus = 0;
                        break;
                    }
                }
                if (StoreActivityEnum.LT002.getDicCode().equals(rewardRule.getExpressionField())){
                    Map<String, Object> map = new HashMap<>();
                    map.put("date", new Date());
                    if (!IKExpressionUtil.executeIs("date" + rewardRule.getExpression(), map)){
                        rewardStatus = 3;
                        break;
                    }
                }
            }
        }

        result.setRewardStatus(rewardStatus);
        return ResponseData.success(result);
    }

    /**
     * 当前排名
     * @param compareList
     * @param storeId
     * @return
     */
    private Integer getRanking(List<CompareActResp> compareList,Long storeId){
        if (CollUtil.isNotEmpty(compareList)) {
            for (CompareActResp actResp : compareList) {
                if (storeId.equals(actResp.getStoreId())) {
                    return compareList.indexOf(actResp) + 1;
                }
            }
        }
        return null;
    }


    private int getRemain(Long actId, Long storeId, MtActivityRule hjRule) {
        int count = mtActivityAppService.processCount(actId, storeId);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        boolean flag = IKExpressionUtil.executeIs("count" + hjRule.getExpression(), map);
        if (!flag) {
            return 0;
        }
        Integer remain = IKExpressionUtil.executeInt("count /" + hjRule.getConditionValue(), map);
        if (ObjectUtil.isEmpty(remain)) {
            return 0;
        }
        return remain - mtActivityAppService.prizeCount(actId, storeId);
    }

    @Log
    @Token
    @PostMapping("/again")
    @ApiOperation("重新上传图片")
    public ResponseData againUp(@RequestBody MtUploadPicReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        MtUserJoinActivityApply apply = mtActivityAppService.selectUserJoinByIdAndUId(req.getId(), storeInfo.getId());
        if (ObjectUtil.isEmpty(apply) || apply.getStatus() != 0) {
            return ResponseData.fail("参加活动的状态不正确");
        }
        MtActivityRule rule = mtActivityAppService.selectRuleByMoldAndActId(req.getId(), StoreActivityEnum.CJ000.getDicType());
        if (ObjectUtil.isEmpty(rule) || rule.getExpressionField().equals(StoreActivityEnum.CJ002.getDicCode())) {
            return ResponseData.fail("此活动不需要上传图片");
        }
        if (rule.getExpressionField().equals(StoreActivityEnum.CJ003.getDicCode())) {
            MtUserJoinActivityProcess process = mtActivityAppService.processByActIdAndCode(req.getId(), (byte) 1, storeInfo.getId());
            if (ObjectUtil.isEmpty(process)) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "堆头活动，重新上传图片只允许上传今天上传的图片");
            }
            MtUserJoinActivityProcess record = new MtUserJoinActivityProcess();
            record.setId(process.getId());
            record.setPicture(req.getPicture());
            return mtActivityAppService.updateProcess(record) > 0 ? ResponseData.success(CodeIdEnum.Success) : ResponseData.fail("上传失败");
        }
        if (mtActivityAppService.processCount(req.getId(), storeInfo.getId()) <= 0) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "集赞活动还未上传过图片");
        }
        MtUserJoinActivityProcess process = mtActivityAppService.processByActIdAndCode(req.getId(), null, storeInfo.getId());
        MtUserJoinActivityProcess record = new MtUserJoinActivityProcess();
        record.setId(process.getId());
        record.setPicture(req.getPicture());
        return mtActivityAppService.updateProcess(record) > 0 ? ResponseData.success(CodeIdEnum.Success) : ResponseData.fail("上传失败");
    }

    @Log
    @Token
    @PostMapping("/up_count")
    @ApiOperation("上传集赞结果")
    public ResponseData upCount(@RequestBody MtUploadPicReq req) {
        if (req.getId() == null || req.getCount() == null) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "id或上传的结果不可为空");
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        MtActivity activity = mtActivityAppService.selectBaseById(req.getId());
        if (ObjectUtil.isEmpty(activity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到需要操作的数据");
        }
        if (activity.getStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "活动状态不正确");
        }
        if (System.currentTimeMillis() > activity.getEndTime().getTime()) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "该活动已结束");
        }
        MtUserJoinActivityApply apply = mtActivityAppService.selectUserJoinByIdAndUId(req.getId(), storeInfo.getId());
        if (ObjectUtil.isEmpty(apply) || apply.getStatus() != 0) {
            return ResponseData.fail("参加活动的状态不正确");
        }
        MtActivityRule rule = mtActivityAppService.selectRuleByFieldAndActId(req.getId(), StoreActivityEnum.CJ001.getDicCode());
        if (ObjectUtil.isEmpty(rule)) {
            return ResponseData.fail("此活动非集赞活动不需要上传结果");
        }
        if (mtActivityAppService.processCount(req.getId(), storeInfo.getId()) <= 0) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "集赞活动还未上传过图片");
        }
        MtUserJoinActivityProcess process = mtActivityAppService.processByActIdAndCode(req.getId(), null, storeInfo.getId());
        MtUserJoinActivityProcess record = new MtUserJoinActivityProcess();
        record.setId(process.getId());
        record.setBizValue(req.getCount());
        return mtActivityAppService.updateProcess(record) > 0 ? ResponseData.success(CodeIdEnum.Success) : ResponseData.fail("上传失败");
    }

    @Log
    @Token
    @PostMapping("/upload")
    @ApiOperation("上传活动图片")
    public ResponseData upPic(@RequestBody MtUploadPicReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        MtActivity activity = mtActivityAppService.selectBaseById(req.getId());
        if (ObjectUtil.isEmpty(activity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到需要操作的数据");
        }
        if (activity.getStatus() != 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "活动状态不正确");
        }
        if (System.currentTimeMillis() > activity.getEndTime().getTime()) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "该活动已结束");
        }
        MtUserJoinActivityApply apply = mtActivityAppService.selectUserJoinByIdAndUId(req.getId(), storeInfo.getId());
        if (ObjectUtil.isEmpty(apply) || apply.getStatus() != 0) {
            return ResponseData.fail("参加活动的状态不正确");
        }
        MtActivityRule rule = mtActivityAppService.selectRuleByMoldAndActId(req.getId(), StoreActivityEnum.HJ000.getDicType());
        if (ObjectUtil.isEmpty(rule)) {
            return ResponseData.fail("未找到活动规则");
        }
        if (rule.getExpressionField().equals(StoreActivityEnum.HJ001.getDicCode()) || rule.getExpressionField().equals(StoreActivityEnum.HJ004.getDicCode())) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "此活动不需要上传图片");
        }
        MtUserJoinActivityApply userJoin = mtActivityAppService.selectUserJoinByIdAndUId(req.getId(), storeInfo.getId());
        if (ObjectUtil.isEmpty(userJoin)) {
            return ResponseData.fail("还没参加此活动");
        }
        if (rule.getExpressionField().equals(StoreActivityEnum.HJ002.getDicCode())) {
            if (mtActivityAppService.processCount(req.getId(), storeInfo.getId()) > 0) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "此活动已经上传过图片不可重复上传");
            }
        } else if (rule.getExpressionField().equals(StoreActivityEnum.HJ003.getDicCode())) {
            int count = mtActivityAppService.processCount(req.getId(), storeInfo.getId());
            if (count >= Integer.parseInt(rule.getConditionValue())) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "此活动图片已上传完成");
            }
            if (count != 0) {
                MtUserJoinActivityProcess toDayProcess = mtActivityAppService.processByActIdAndCode(req.getId(), (byte) 1, storeInfo.getId());
                if (ObjectUtil.isNotEmpty(toDayProcess)) {
                    return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "今天已经上传过图片一天内不可重复上传");
                }
                MtUserJoinActivityProcess process = mtActivityAppService.processByActIdAndCode(req.getId(), (byte) 0, storeInfo.getId());
                if (ObjectUtil.isEmpty(process)) {
                    return ResponseData.fail("该活动为连续上传，昨天未上传图片，已被淘汰");
                }
            }
        }
        MtUserJoinActivityProcess record = new MtUserJoinActivityProcess();
        record.setActId(req.getId());
        record.setBizValue(req.getCount());
        record.setUserArea(storeInfo.getAreaId());
        record.setUserImage(storeInfo.getStoreImage());
        record.setActName(activity.getName());
        record.setActStart(activity.getStartTime());
        record.setActEnd(activity.getEndTime());
        record.setUserAccountId(storeInfo.getId());
        record.setUserLoginName(storeInfo.getStoreBoss());
        record.setUserPhone(storeInfo.getConnectWay());
        record.setPicture(req.getPicture());
        record.setDicCode(rule.getExpressionField());
        record.setCreatedAt(new Date());
        return mtActivityAppService.insertProcess(record);
    }

    @Log
    @Token
    @GetMapping("/compare")
    @ApiOperation("排名活动门店排名列表")
    public ResponseData<List<CompareActResp>> compareAct(@RequestParam(value = "id", required = true) Long id) {
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        MtActivity activity = mtActivityAppService.selectBaseById(id);
        if (ObjectUtil.isEmpty(activity)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到改活动");
        }
        MtActivityRule rule = mtActivityAppService.selectRuleByMoldAndActId(id, StoreActivityEnum.PB000.getDicType());
        if (ObjectUtil.isEmpty(rule)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "此活动非排名活动");
        }
        MtActivityRule hjRule = mtActivityAppService.selectRuleByMoldAndActId(id, StoreActivityEnum.HJ000.getDicType());
        if (ObjectUtil.isEmpty(hjRule)) {
            return ResponseData.fail("未找到活动规则");
        }
        MtActivityRule activityRule = mtActivityAppService.selectRuleByFieldAndActId(activity.getId(), StoreActivityEnum.HJ002.getDicCode());
        if (ObjectUtil.isEmpty(activityRule)) {
            List<CompareActResp> result = null;
            if (StoreActivityEnum.PB001.getDicCode().equals(rule.getExpressionField())) {
                //全部排名
                result = mtActivityAppService.selectCompareAct(activity.getId(), null);
            } else if (StoreActivityEnum.PB002.getDicCode().equals(rule.getExpressionField())) {
                //大区排名
                result = mtActivityAppService.selectCompareAct(activity.getId(), storeInfo.getAreaId());
            }
            if (CollectionUtils.isEmpty(result)){
                return ResponseData.success(null);
            }
            return compareActResp(result, rule, hjRule.getConditionValue());
        }
        List<CompareActResp> result = null;
        if (StoreActivityEnum.PB001.getDicCode().equals(rule.getExpressionField())) {
            //全部排名
            result = mtActivityAppService.selectCompareActJiZan(activity.getId(), null);
        } else if (StoreActivityEnum.PB002.getDicCode().equals(rule.getExpressionField())) {
            //大区排名
            result = mtActivityAppService.selectCompareActJiZan(activity.getId(), storeInfo.getAreaId());
        }
        return compareActResp(result,rule, hjRule.getConditionValue());
    }

    @Log
    @Token
    @PostMapping("/lottery")
    @ApiOperation("抽奖")
    public ResponseData<String> lotteryAct(@RequestBody IdReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MtActivity activity = mtActivityAppService.selectMtActivity(req.getId());
        if(ObjectUtil.isEmpty(activity)){
            return ResponseData.fail("未找到此活动");
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        MtUserJoinActivityApply apply = mtActivityAppService.selectUserJoinByIdAndUId(req.getId(), storeInfo.getId());
        if (ObjectUtil.isEmpty(apply) || apply.getStatus() == -1 || apply.getStatus() == 2) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "参加此活动的状态不正确");
        }
        MtActivityRule hjRule = mtActivityAppService.selectRuleByMoldAndActId(req.getId(), StoreActivityEnum.HJ000.getDicType());
        if (ObjectUtil.isEmpty(hjRule)) {
            return ResponseData.fail("未找到此活动的规则");
        }
        if (!isRewardTime(req.getId())) {
            return ResponseData.fail("不在抽奖时间内,无法抽奖");
        }
        int remain = getRemain(req.getId(), storeInfo.getId(), hjRule);
        if (remain <= 0) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "没有剩余的抽奖次数");
        }
        List<MtActivityRule> ruleList = mtActivityAppService.selectRuleList(req.getId(), StoreActivityEnum.GS001.getDicType());
        if (CollUtil.isEmpty(ruleList)) {
            return ResponseData.fail("未找到该抽奖活动的获奖金额");
        }
        List<MtActivityRule> newList = new ArrayList<>();
        for (MtActivityRule rule : ruleList) {
            if (Integer.parseInt(rule.getConditionValue()) <= 0) {
                continue;
            }
            newList.add(rule);
        }
        if (CollUtil.isEmpty(newList)) {
            for (MtActivityRule rule : ruleList) {
                rule.setConditionValue(rule.getExpression());
                mtActivityAppService.updateRule(rule);
            }
            newList = ruleList;
        }
        List<MtActivityRule> randomList = new ArrayList<>();
        for (MtActivityRule rule : newList) {
            int i = Integer.parseInt(rule.getConditionValue());
            for (int j = 0; j < i; j++) {
                randomList.add(rule);
            }
        }
        MtActivityRule gsRule = randomList.get(RandomUtil.randomInt(0, randomList.size()));
        gsRule.setConditionValue((Integer.parseInt(gsRule.getConditionValue()) - 1) + "");
        if (mtActivityAppService.updateRule(gsRule) <= 0) {
            return ResponseData.fail("操作失败");
        }
        //TODO:需要打钱操作
        MtUserJoinActivityPrize prize = new MtUserJoinActivityPrize();
        prize.setActId(activity.getId());
        prize.setActName(activity.getName());
        prize.setActStart(activity.getStartTime());
        prize.setActEnd(activity.getEndTime());
        prize.setUserAccountId(storeInfo.getId());
        prize.setUserLoginName(storeInfo.getStoreName());
        prize.setUserPhone(storeInfo.getConnectWay());
        prize.setBizId(activity.getId());
        prize.setPrize(new BigDecimal(gsRule.getConditions()).multiply(new BigDecimal(100)).toString());
        prize.setCreatedAt(new Date());
        mtActivityAppService.insertPrize(prize);
        return ResponseData.success(gsRule.getConditions());
    }

    private boolean isEnrollTime(Long actId) {
        List<MtActivityRule> sbRule = mtActivityAppService.selectRuleList(actId, StoreActivityEnum.SB001.getDicType());
        return isTime(sbRule);
    }

    private boolean isRewardTime(Long actId) {
        List<MtActivityRule> ljRule = mtActivityAppService.selectRuleList(actId, StoreActivityEnum.LT000.getDicType());
        return isTime(ljRule);
    }

    private boolean isTime(List<MtActivityRule> ljRule) {
        if (CollUtil.isNotEmpty(ljRule)) {
            Map<String, Object> map = new HashMap<>();
            map.put("date", new Date());
            for (MtActivityRule rule : ljRule) {
                String ex = "date" + rule.getExpression();
                if (!IKExpressionUtil.executeIs(ex, map)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    private ResponseData<List<CompareActResp>> compareActResp(List<CompareActResp> result,MtActivityRule rule, String hjValue) {
        if (CollUtil.isNotEmpty(result)) {
            result.get(0).setDicCode(rule.getExpressionField());
            result.removeIf(resp -> resp.getSale() < Integer.parseInt(hjValue));
            if (CollUtil.isNotEmpty(result)) {
                if (result.size() <= Integer.parseInt(rule.getConditionValue())) {
                    saveStore(result);
                    return ResponseData.success(result);
                }
                Integer sale = result.get(Integer.parseInt(rule.getConditionValue()) - 1).getSale();
                result.removeIf(resp -> resp.getSale() < sale);
            }
        }
        if(CollUtil.isNotEmpty(result)){
            saveStore(result);
        }
        return ResponseData.success(result);
    }

    private void saveStore(List<CompareActResp> list){
        for (CompareActResp actResp : list) {
            SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(actResp.getStoreId());
            if(ObjectUtil.isNotEmpty(storeInfo)){
                actResp.setImage(storeInfo.getStoreImage());
                actResp.setStoreName(storeInfo.getStoreName());
            }
        }
    }

    @Log
    @Token
    @GetMapping("/record")
    @ApiOperation("活动记录")
    public ResponseData<PageInfo<MtActivityRecordDetailResp>> recordPage(PageRequest req){
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(Long.parseLong(getAttribute()));
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到登录的门店");
        }
        PageInfo<MtActivityRecordDetailResp> info = mtActivityAppService.selectRecordDetail(req, storeInfo.getId());
        List<MtActivityRecordDetailResp> resps = info.getList();
        for (MtActivityRecordDetailResp resp : resps) {
            if(resp.getStatus() == 3){
                //TODO:返回奖励
            }
            if(StoreActivityEnum.CJ002.getDicCode().equals(resp.getDicCode())){
                int count = mtActivityAppService.processCount(resp.getId(), storeInfo.getId());
                resp.setLottery(count);
            }
            MtActivityRule rule = mtActivityAppService.selectRuleByMoldAndActId(resp.getId(), StoreActivityEnum.PB000.getDicType());
            if(ObjectUtil.isEmpty(rule)){
                continue;
            }
            List<CompareActResp> result = null;
            if (StoreActivityEnum.PB001.getDicCode().equals(rule.getExpressionField())) {
                //全部排名
                result = mtActivityAppService.selectCompareAct(resp.getId(), null);
            } else if (StoreActivityEnum.PB002.getDicCode().equals(rule.getExpressionField())) {
                //大区排名
                result = mtActivityAppService.selectCompareAct(resp.getId(), storeInfo.getAreaId());
            }
            resp.setRankingStandard(rule.getConditionValue());
            resp.setRankingCurrent(String.valueOf(getRanking(result,storeInfo.getId())));
        }

        return ResponseData.success(info);
    }
}
